package com.itheima.controller;

import lombok.extern.slf4j.Slf4j;
import com.itheima.common.R;
import com.itheima.pojo.StaffMessage;
import com.itheima.service.StaffMessageService;
import com.itheima.utils.JWTUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

//@RestController注解就是@ResponseBody ＋ @Controller合在一起的作用。

/**
 * @author 林晓伟
 */
@Slf4j
@RestController
@RequestMapping(value = "/employee", produces = "application/json;charset=utf-8")
public class StaffMessageController {
    @Resource
    private StaffMessageService staffMessageService;
    @Resource
    private RedisTemplate<String, String> stringRedisTemplate;

    /**
     * H04-新增员工
     */
    @PostMapping
    public R add(@RequestBody StaffMessage staffMessage) {
        Integer judge = staffMessageService.judge(staffMessage.getUsername());
        if (judge != 0) {
            return R.error("该账号已存在！请重新输入");
        }
        Integer add = staffMessageService.add(staffMessage);
        if (add != 0) {
            return R.success("添加成功！");
        }
        return R.error("添加失败！请重试");
    }

    /**
     * H05-启用/禁用/修改
     */
    @PutMapping
    public R update(@RequestBody StaffMessage staffMessage) {
        Integer judge = staffMessageService.judge(staffMessage.getUsername());
        if (judge != 0) {
            return R.error("该账号已存在！请重新输入");
        }
        Integer update = staffMessageService.update(staffMessage);
        if (update != 0) {
            return R.success("员工信息修改成功！");
        }
        return R.error("员工信息修改失败！");
    }

    /**
     * H01-员工登录
     */
    @PostMapping("/login")
    @ResponseBody
    public R j(@RequestBody StaffMessage staffMessage) {
        try {
            //md5解密
            String password = staffMessage.getPassword();
            password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
            staffMessage.setPassword(password);

            if (staffMessageService.longin(staffMessage).size() == 0) {
                return R.error("登陆失败");
            } else {
                List<StaffMessage> userDB = staffMessageService.longin(staffMessage);

                Map<String, String> payload = new HashMap<>();

                payload.put("username", userDB.get(0).getUsername());

                String token = JWTUtils.getToken(payload);
                userDB.get(0).setToken(token);

                stringRedisTemplate.opsForValue().set("token", token, 7, TimeUnit.DAYS);
                return R.success(userDB);
            }
        } catch (Exception e) {
            System.out.println("error===========员工登录");
        }
        return R.error("用户名或者密码错误");
    }

    /**
     * H02-员工登出
     */
    @PostMapping("/logout")
    public R staffDelete() {
        Boolean aBoolean = staffMessageService.staffDelete();
        return aBoolean ? R.success("登出成功") : R.error("登出失败！");
    }

    /**
     * H03-员工分页查询
     * @param name 名字
     * @param page 页数
     * @param pageSize 每页条数
     */
    @GetMapping("/page")
    public R s(@RequestParam(value = "name", required = false) String name,
               @RequestParam Integer page,
               @RequestParam Integer pageSize) {
        return staffMessageService.select(page, pageSize, name);
    }

//- 名称：@PathVariable
//- 类型：形参注解
//- 位置：SpringMVC控制器方法形参定义前面
//- 作用：绑定路径参数与处理器方法形参间的关系，要求路径参数名与形参名一一对应
//    和形参名字要对应
//    根据id查询

    /**
     * H03-根据id查询员工信息
     */
    @GetMapping("/{id}")
    public R findById(@PathVariable Integer id) {
        StaffMessage byId = staffMessageService.findById(id);
        if (byId != null) {
            return R.success(byId);
        }
        return R.error("查询失败！");
    }
}
